package com.spring.raft.websocket;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.raft.service.RaftNodeService;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.socket.*;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.net.URI;
import java.util.concurrent.CompletableFuture;

@Component
public class WebSocketClient {

    private final ObjectMapper objectMapper = new ObjectMapper();
    private WebSocketSession session;

    private final String serverUri = "ws://localhost:8080/ws"; // WebSocket 服务器地址

    @Bean
    public WebSocketConnectionManager webSocketConnectionManager() {
        WebSocketConnectionManager manager = new WebSocketConnectionManager(
                new StandardWebSocketClient(),
                new MyWebSocketHandler(),
                serverUri
        );
        manager.setAutoStartup(true);  // 自动启动 WebSocket 连接
        return manager;
    }

    private static class MyWebSocketHandler extends TextWebSocketHandler {
        @Override
        public void afterConnectionEstablished(org.springframework.web.socket.WebSocketSession session) {
            System.out.println("✅ WebSocket 客户端已连接到服务器：" + session.getUri());
        }
    }

    public void sendMessage(RaftNodeService.RaftRequest request) {
        if (session != null && session.isOpen()) {
            try {
                String message = objectMapper.writeValueAsString(request);
                session.sendMessage(new TextMessage(message));
            } catch (Exception e) {
                System.err.println("❌ 发送消息失败: " + e.getMessage());
            }
        }
    }

    private class WebSocketHandler extends AbstractWebSocketHandler {

        @Override
        public void afterConnectionEstablished(WebSocketSession session) {
            System.out.println("🔗 客户端 WebSocket 连接成功！");
        }

        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            System.out.println("📩 客户端收到消息: " + message.getPayload());

            // 解析消息
            var request = objectMapper.readValue(message.getPayload(), RaftNodeService.RaftRequest.class);

            // 处理 Raft 请求
            processRaftResponse(request);
        }

        private void processRaftResponse(RaftNodeService.RaftRequest request) {
            switch (request.type) {
                case "RequestVote":
                    System.out.println("🔵 收到投票请求: " + request.nodeId);
                    break;
                case "VoteGranted":
                    System.out.println("🟢 收到投票: " + request.nodeId);
                    break;
                case "AppendEntries":
                    System.out.println("💖 Leader 心跳包: " + request.nodeId);
                    break;
                default:
                    System.out.println("⚠️ 未知消息类型: " + request.type);
            }
        }

        @Override
        public void handleTransportError(WebSocketSession session, Throwable exception) {
            System.err.println("❌ WebSocket 传输错误: " + exception.getMessage());
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
            System.out.println("🔌 WebSocket 连接关闭: " + status);
        }
    }
}
